package com.twu.biblioteca.Command;

import com.twu.biblioteca.BibiliotecaModel;
import com.twu.biblioteca.User;
import com.twu.biblioteca.Bibilioteca;

import java.io.PrintWriter;

public class LoginCommand implements IBibiliotecaCommand {
    private PrintWriter out;
    private Bibilioteca bibilioteca;

    public LoginCommand(Bibilioteca bibilioteca) {
        this.bibilioteca = bibilioteca;
    }

    public void ICommand(PrintWriter outputBuffer) {
        out = outputBuffer;
        login();
    }

    private void login() {
        if (!bibilioteca.isLogged()) {
            out.println("enter your userName and password for login");
            if (!bibilioteca.getScanner().hasNext())
                return;
            String username = bibilioteca.getScanner().next();
            if (!bibilioteca.getScanner().hasNext())
                return;
            String password = bibilioteca.getScanner().next();
            if (!userAuthenticate(username, password)) {
                out.println("userName or password is wrong");
                return;
            } else {
                out.println("You are successful logged");
                return;
            }
        } else {
            out.println("You already logged");
            return;
        }

    }

    private boolean userAuthenticate(String userName, String password) {
        for (int i = 0; i < BibiliotecaModel.getUsers().size(); i++) {
            User user = BibiliotecaModel.getUsers().get(i);
            if (user.getUserName().equals(userName) && user.getPassword().equals(password)) {
                bibilioteca.setLoggedUser(user);

                return true;
            }
        }
        return false;
    }


}
